/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.dishes.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.dishes.DishesMenuBranchRepository;
import com.qinyeit.serviceapp.repository.dishes.DishesMenuDetailRepository;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.dishes.*;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.sun.org.apache.regexp.internal.RECompiler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.qinyetech.springstage.core.service.BaseService;
import com.qinyeit.serviceapp.repository.dishes.DishesMenuRepository;

import java.util.Date;
import java.util.List;
import java.util.Map;

/** 
 * ClassName: DishesMenuServiceImpl <br/> 
 * Function: 菜谱 业务实现 <br/> 
 * date: 2018-11-26 10:29:38 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class DishesMenuServiceImpl extends BaseService<DishesMenu, Long> implements DishesMenuService {


	@Autowired
	private DishesMenuRepository dishesMenuRepository;
	@Autowired
	private BranchService branchService;
	@Autowired
	private DishesMenuBranchRepository dishesMenuBranchRepository;
	@Autowired
	private DishesMenuDetailRepository dishesMenuDetailRepository;
	@Autowired
	private BranchDataReleasedServiceImpl branchDataReleasedService;
	@Autowired
	private DishesStoreService dishesStoreService;
	@Autowired
	private DishesService dishesService;
	@Autowired
	private MaterialService materialService;
	@Autowired
	private SyncDishesRecordService syncDishesRecordService;


	@Override
	public void saveData(JSONObject data, Long merchantGroupId,String operator) {

		log.info("data : {}",data);

		JSONObject menuData = data.getJSONObject("dishesMenus");
		JSONArray branchData = data.getJSONArray("branchs");
		if(menuData==null){
			throw new BusinessRunTimeException("菜谱信息为空",10001);
		}
		if(StringUtils.isBlank(menuData.getString("name"))){
			throw new BusinessRunTimeException("菜谱名称不能为空",10002);
		}
		Long id = menuData.getLong("id");
		boolean boo =this.exists(SearchUtils.buildExists(id,"name",menuData.getString("name"),merchantGroupId));
		if(boo){
			throw new BusinessRunTimeException("名称已存在",10003);
		}

		if(menuData.getLong("storeId")==null){
			throw new BusinessRunTimeException("请选择菜品库",10004);
		}

		if(CollectionUtils.isEmpty(branchData)){
			throw new BusinessRunTimeException("请选择适用门店",10005);
		}

		//是否是发布新品
		boolean isNew = data.getBoolean("isNew");
		DishesMenu menu = null;
		if(id==null){
			menu = new DishesMenu();
		}else {
			menu = this.findById(id);
			//清除所属门店 和 菜品信息
			dishesMenuRepository.deleteDishesMenuBranch(id);
			dishesMenuRepository.deleteDishesMenuDetail(id);
		}
		menu.setName(menuData.getString("name"));
		menu.setEffectiveTime(menuData.getDate("effectiveTime"));
		menu.setOperateTime(DateUtils.date());
		menu.setOperatorName(operator);
		menu.setStoreId(menuData.getLong("storeId"));
		menu.setMerchantGroupId(merchantGroupId);
		if(isNew){
			List<Long> ids = JSON.parseArray(menu.getDishesDetails(),Long.class);
			if (CollectionUtils.isNotEmpty(ids)){
				if (StringUtils.isNotBlank(menuData.getString("dishes"))){
					ids.addAll(JSON.parseArray(menuData.getString("dishes"),Long.class));
				}
			}else {
				ids = Lists.newArrayList();
				if (StringUtils.isNotBlank(menuData.getString("dishes"))){
					ids.addAll(JSON.parseArray(menuData.getString("dishes"),Long.class));
				}
			}
			menu.setDishesDetails(JSON.toJSONString(ids));
		}else {
			menu.setDishesDetails(menuData.getString("dishes"));
		}
		menu.setMaterialDetails(menuData.getString("materials"));
		menu.setCostCard(menuData.getBoolean("costCard"));
		menu = this.update(menu);

		DishesMenuBranch branch = null;
		Branch br = null;
		Map<Long,Boolean> changeBranch = Maps.newHashMap();
		List<DishesMenuBranch> branchList = Lists.newArrayList();
		for (int i = 0; i < branchData.size(); i++) {
			branch = new DishesMenuBranch();
			br = branchService.findById(branchData.getLong(i));
			if (br==null){
				throw new BusinessRunTimeException("门店不存在",10002);
			}
			//门店没有保存菜品库id(删除) 或者 没有改变菜品库 用于后续的数据下发 是否删除其他菜品库的数据
			if(br.getDishesStoreId()==null){//第一次下发 删除菜品信息
				changeBranch.put(br.getMerchantId(),true);
			}else if(br.getDishesStoreId()==menu.getStoreId()){ // 没有改变菜品库
				changeBranch.put(br.getMerchantId(),false);
			}else { //改变菜品库 删除菜品信息
				changeBranch.put(br.getMerchantId(),true);
			}
			br.setDishesStoreId(menu.getStoreId());
			branchService.update(br);
			branch.setBranchId(branchData.getLong(i));
			branch.setMenuId(menu.getId());
			branch.setDistrictId(br.getDistrictId());
			branch.setMerchantGroupId(merchantGroupId);
			branchList.add(branch);
		}
		dishesMenuBranchRepository.saveAll(branchList);

		//下发数据
		List<Long> bIDs = branchData.toJavaList(Long.class);
		List<Long> dIDs = JSON.parseArray(menu.getDishesDetails(), Long.class);
		List<Long> mIDs = JSON.parseArray(menu.getMaterialDetails(),Long.class);


		log.info("is new  : {}",isNew);

		branchDataReleasedService.releasedDishesAndMaterial(menu,bIDs,changeBranch,merchantGroupId,isNew);

		//保存下发记录
		Branch branchMerchant = branchService.findById(bIDs.get(0));
		DishesStore store = dishesStoreService.findById(menu.getStoreId());
		SyncDishesRecord record = new SyncDishesRecord();
		record.setBranchId(branchMerchant.getId());
		record.setBranchName(branchMerchant.getName());
		record.setIssueTime(DateUtils.date());
		record.setMenuId(menu.getId());
		record.setOperatorName(operator);
		record.setStoreId(menu.getStoreId());
		record.setStoreName(store.getName());
		record.setMerchantGroupId(merchantGroupId);

		List<QyMap> mapList= Lists.newArrayList();
		QyMap qyMap = null;
		//商品信息
		Dishes dishes = null;
		QyMap map = QyMap.NEW();
		if(CollectionUtils.isNotEmpty(dIDs)){
			for (Long item : dIDs) {
				dishes = dishesService.findById(item);
				dishes.setHasIssue(true);
				dishesService.update(dishes);
			}
		}

		List<Long> dids = JSON.parseArray(menuData.getString("dishes"),Long.class);

		if(CollectionUtils.isNotEmpty(dids)){
			List<String> codes = null;
			for (Long item : dids) {
				dishes = dishesService.findById(item);
				dishes.setHasIssue(true);
				dishesService.update(dishes);
				qyMap = QyMap.map("name",dishes.getName())
						.setv("id",dishes.getId())
						.setv("unit",dishes.getUnit())
						.setv("price",dishes.getPrice())
						.setv("categoryName",dishes.getCategory().getName())
						.setv("type",dishes.getType().getText())
						.setv("vipPrice",dishes.getVipPrice())
						.setv("no",dishes.getNo());
				codes = JSON.parseArray(dishes.getCode(),String.class);
				if(CollectionUtils.isNotEmpty(codes)){
					qyMap.setv("code",codes.get(0));
					qyMap.setv("codes",codes);
				}
				mapList.add(qyMap);
			}
			map.setv("dishes",mapList);
		}

		//原料信息
		Material material = null;
		if(CollectionUtils.isNotEmpty(mIDs)){
			mapList = Lists.newArrayList();
			for (Long item : mIDs) {
				material = materialService.findById(item);
				qyMap = QyMap.map("name",material.getName())
						.setv("id",material.getId())
						.setv("unit",material.getUnit())
						.setv("goodsSpec",material.getGoodsSpec())
						.setv("categoryName",material.getCategory().getName())
						.setv("no",material.getNo())
						.setv("type",material.getMaterialType().getText());
				mapList.add(qyMap);
			}
			map.setv("materials",mapList);
		}
		map.setv("costCard",menu.getCostCard());
		record.setContent(JSON.toJSONString(map));
		syncDishesRecordService.save(record);
	}

	@Override
	public void deletedMenuDetails(Long id) {
		dishesMenuRepository.deleteDishesMenuBranch(id);
		dishesMenuRepository.deleteDishesMenuDetail(id);
	}
}